package com.micro.ai.template.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.template.entity.TemplateFavorite;
import com.micro.ai.template.service.TemplateFavoriteService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 模板收藏Controller
 *
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/template/favorites")
@RequiredArgsConstructor
@Tag(name = "模板收藏管理", description = "模板收藏相关接口")
public class TemplateFavoriteController {

    private final TemplateFavoriteService templateFavoriteService;

    @PostMapping("/template/{templateId}")
    @PreAuthorize("hasAuthority('template:favorite:create')")
    @Operation(summary = "收藏模板", description = "将模板添加到收藏夹")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "收藏成功",
            content = @Content(schema = @Schema(implementation = TemplateFavorite.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "模板不存在")
    })
    public ApiResponse<TemplateFavorite> favoriteTemplate(
            @Parameter(description = "模板ID") @PathVariable String templateId,
            Authentication authentication) {
        String userId = authentication.getName();
        log.info("收藏模板请求, templateId: {}, userId: {}", templateId, userId);
        return ApiResponse.success(templateFavoriteService.favoriteTemplate(templateId, userId));
    }

    @DeleteMapping("/template/{templateId}")
    @PreAuthorize("hasAuthority('template:favorite:delete')")
    @Operation(summary = "取消收藏", description = "从收藏夹中移除模板")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "取消成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "收藏记录不存在")
    })
    public ApiResponse<Void> unfavoriteTemplate(
            @Parameter(description = "模板ID") @PathVariable String templateId,
            Authentication authentication) {
        String userId = authentication.getName();
        log.info("取消收藏请求, templateId: {}, userId: {}", templateId, userId);
        templateFavoriteService.unfavoriteTemplate(templateId, userId);
        return ApiResponse.<Void>success(null);
    }

    @GetMapping("/template/{templateId}/check")
    @PreAuthorize("hasAuthority('template:favorite:query')")
    @Operation(summary = "检查是否已收藏", description = "检查当前用户是否已收藏该模板")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<Map<String, Boolean>> checkFavorited(
            @Parameter(description = "模板ID") @PathVariable String templateId,
            Authentication authentication) {
        String userId = authentication.getName();
        boolean favorited = templateFavoriteService.isFavorited(templateId, userId);
        
        Map<String, Boolean> result = new HashMap<>();
        result.put("favorited", favorited);
        
        return ApiResponse.success(result);
    }

    @GetMapping("/user")
    @PreAuthorize("hasAuthority('template:favorite:query')")
    @Operation(summary = "查询用户收藏列表", description = "分页查询当前用户的收藏列表")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<IPage<TemplateFavorite>> getUserFavorites(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer size,
            Authentication authentication) {
        String userId = authentication.getName();
        Page<TemplateFavorite> page = new Page<>(current, size);
        return ApiResponse.success(templateFavoriteService.getUserFavorites(userId, page));
    }

    @GetMapping("/template/{templateId}/count")
    @Operation(summary = "查询收藏数", description = "获取模板的收藏总数")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "模板不存在")
    })
    public ApiResponse<Map<String, Long>> getFavoriteCount(
            @Parameter(description = "模板ID") @PathVariable String templateId) {
        long count = templateFavoriteService.getFavoriteCount(templateId);
        
        Map<String, Long> result = new HashMap<>();
        result.put("count", count);
        
        return ApiResponse.success(result);
    }
}

